/**
 * 图片压缩
 * @explain 借助canvas对图片进行重绘（canvas2DataURL）
 * @param base64Url	base64格式的图片字符串
 * @param imgAttr	重绘图片宽度、高度、质量等属性的设置
 * @param callback	该函数执行完毕后，要执行的回调函数
 * @returns
 */
let index = 0;
export const compress = function (base64Url, imgAttr, callback) {
    var img = new Image();
    img.src = base64Url;
    img.onload = function () {
        var that = this;
        // 默认按比例压缩
        var w = that.width,
            h = that.height,
            // 宽高比例
            scale = w / h;
        w = imgAttr.width || w;
        h = imgAttr.height || (w / scale);
        // 默认图片质量为0.7
        var quality = 0.1;
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        canvas.setAttributeNode(anw);
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // 图像质量（0-1）
        if (imgAttr.quality && imgAttr.quality <= 1 && imgAttr.quality > 0) {
            quality = imgAttr.quality;
        }
        // 重绘后的图片类型
        var imgType = imgAttr.type || 'image/jpeg';
        // quality值越小，所绘制出的图像越模糊
        var base64 = canvas.toDataURL(imgType, quality);
        if (showSize(base64) > 0.8 * 1024 && index < 5) {
            index++;
            console.log(`重新压缩${showSize(base64)}kb`);
            compress(base64, {
                quality: quality / 2,
            }, (newBase64) => {
                callback(newBase64)
                index = 0;
            })
        } else {
            // 回调函数返回base64的值
            callback(base64);
            index = 0;
        }

    };
}
function showSize(base64url) {
    //把头部去掉
    let str = base64url.replace("data:image/png;base64,", "");
    // 找到等号，把等号也去掉
    let equalIndex = str.indexOf("=");
    if (str.indexOf("=") > 0) {
        str = str.substring(0, equalIndex);
    }
    // 原来的字符流大小，单位为字节
    let strLength = str.length;
    // 计算后得到的文件流大小，单位为字节
    let fileLength = parseInt(strLength - (strLength / 8) * 2);
    // 由字节转换为kb
    let size = "";
    size = (fileLength / 1024).toFixed(2);
    let sizeStr = size + ""; //转成字符串
    let index = sizeStr.indexOf("."); //获取小数点处的索引
    let dou = sizeStr.substr(index + 1, 2); //获取小数点后两位的值
    if (dou == "00") {
        //判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
    }
    return size;
}
/**
* file图片文件转base64
* @param {*} img file文件或者blob
* @param {*} callback function (imgurl)通过参数获得base64
*/
export const getBase64 = function (img, callback) {
    const reader = new FileReader()
    reader.addEventListener('load', () => callback(reader.result))
    reader.readAsDataURL(img)
}

